<?php


namespace App\Repositories;


use App\Exceptions\BasicException;

class RechargeConfigRepository
{
    //新增或编辑充值金额
    public function addOrEditRechargeAmount($param)
    {
        $id = $param['id'] ?? 0;
        $sort = $param['sort'];
        $qipaoCoin = $param['qipao_coin'];
        $rmb = $param['rmb'];
        $status = $param['status'];

        if ($id > 0) {
            $config = app('model_recharge_config')->select('id', 'client_type')->where('id', $id)->first();
            if (empty($config)) throw new BasicException(0, 'id不存在');
            $clientType = $config->client_type;
        } else {
            $clientType = $param['client_type'];
        }

        //检测气泡币或人民币值是否重复
        $where = ['client_type' => $clientType];
        $whereFunc = function ($query) use ($id) {
            if ($id > 0) {
                $query->where('id', '<>', $id);
            }
        };
        $exist = app('model_recharge_config')
            ->where($where)
            ->where($whereFunc)
            ->where('qipao_coin', $qipaoCoin)->first();
        if ($exist) throw new BasicException(0, '冰语币值重复');

        $exist = app('model_recharge_config')
            ->where($where)
            ->where($whereFunc)
            ->where('rmb', $rmb)->first();
        if ($exist) throw new BasicException(0, '人民币值重复');

        $data = [
            'client_type' => $clientType,
            'sort' => $sort,
            'qipao_coin' => $qipaoCoin,
            'rmb' => round($rmb * 100),
            'status' => $status,
        ];

        if ($id > 0) {
            return app('model_recharge_config')->edit($id, $data);
        } else {
            return app('model_recharge_config')->add($data);
        }
    }
}
